import { useState, useEffect } from 'react'
import '../../7_0_redux/index.css'
import ProfileSetting from './ProfileSetting'
// import { createContext } from '../../8_hooks/2_sources/5_useContext';
import { createContext } from 'react';
// import PubSub from 'pubsub-js';
import PubSub from '../sources/pubsub-js';

export const settingContext = createContext({ username: '张三', unReadCount: 1 });

export default function Demo() {
    return <>
        <Header />
        <Setting />

        <p>
            1. 单看通信极度简单，但是需要结合useState才可以造成页面刷新。 <br />
            2. 不可状态集中管理，其实只适合很简单的常见，很少的变量选哟通信的适合。<br />
            如果是很多变量需要通信的，可能就捉襟见肘了。<br />
            3. 但是写法是真的简洁
        </p>
    </>;
}

function Header() {
    const [username, setUsername] = useState('张三');
    const [unReadCount, setUnReadCount] = useState(1);

    useEffect(() => {
        const changeUserNameListener = PubSub.subscribe('changeUsername', (topic, data) => {
            setUsername(data)
            // 此处改了，useContext的地方并没有立刻改变，所以useContext中应该是没有监听功能的吧
            // 也就是Provider中的值应该是useState或者useReducer，这也才会自动刷新
            settingContext._currentValue.username = data;
        })

        const changeUnReadCountListener = PubSub.subscribe('unReadCount', (topic, data) => {
            setUnReadCount(data)
        })
        return () => {
            PubSub.unsubscribe(changeUserNameListener);
            PubSub.unsubscribe(changeUnReadCountListener);
        }
    }, []);

    return (
        <div className='header'>
            <span>{username}</span>
            <span className='un-read'>
                未读
                <div className='un-read-num'>{unReadCount}</div>
            </span>
        </div>
    )
}

function Setting() {
    return (
        <div className='setting'>
            设置页面：
            <ProfileSetting />
        </div>
    );
}

